define([
    "UtilDir/util",
    "UtilDir/tool",
    "UtilDir/org/selectOrg",
    "UtilDir/searchBlock",
    "static/app/cupload",
    'UtilDir/loading',
    "Date", "DateCN", "css!DateCss",
    "EasyUI", "EasyUI-lang"
], function (Util, Tool, SelectOrg, SearchBlock, cupload, Loading) {
    var getHddcCjProjectController = function () {
        return getServer() + "/hddc/hddcCjProjects";
    };
    var getHddcCjTaskController = function () {
        return getServer() + "/hddc/hddcCjTasks";
    };


    // 返回所有项目名称
    var projectData = null;

    function getAllProject() {
        $.ajax({
            url: getHddcCjProjectController() + "/queryAllHddcCjProjects",
            type: "get",
            async: false,
            success: function (data) {
                projectData = data;
            }
        });
        return projectData;
    }

    // 初始化项目名称下拉框
    function initProjectSelect(selectId) {
        var projects = getAllProject();
        var html = '<option value="" disabled selected style="display:none;">请选择</option>';
        $.each(projects, function (idx, item) {
            html += "<option value='" + item.projectName + "'>" + item.projectName + "</option>";
        });
        $("#" + selectId + " option").remove();
        $("#" + selectId).append(html);
    }

    // 根据项目名称找项目id
    function getProjectIdByProjectName(pname) {
        var projectId = null;
        if (projectData != null) {
            for (var i = 0; i < projectData.length; i++) {
                if (projectData[i].projectName == pname) {
                    return projectData[i].projectId;
                }
            }
        }
        return projectId;
    }

    // 根据项目名称返回这个项目的所有任务
    function getAllTaskByProjectName(pname) {
        var projectId = getProjectIdByProjectName(pname);
        var taskdata = [];
        if (projectId != null) {
            $.ajax({
                url: getHddcCjTaskController() + "/findHddcCjTaskEntityByProjectIds/" + projectId,
                type: "get",
                async: false,
                success: function (data) {
                    for (var i = 0; i < data.length; i++) {
                        if (data[i].belongProject == pname) {
                            taskdata.push(data[i]);
                        }
                    }

                }
            });
        }
        return taskdata;
    }

    // 根据项目id返回这个项目的所有任务
    function getAllTaskByProjectId(pid) {
        var taskdata = [];
        if (pid != null) {
            $.ajax({
                url: getHddcCjTaskController() + "/findHddcCjTaskEntityByProjectIds/" + pid,
                type: "get",
                async: false,
                success: function (data) {
                    for (var i = 0; i < data.length; i++) {
                        if (data[i].belongProjectID == pid) {
                            taskdata.push(data[i]);
                        }
                    }

                }
            });
        }
        return taskdata;
    }

    // 返回所有任务
    function getAllTask() {
        var taskdata = [];
        $.ajax({
            url: getHddcCjTaskController() + "/queryAllHddcCjTasks",//queryAllHddcCjProjects
            type: "get",
            async: false,
            success: function (data) {
                taskdata = data;
            }
        });
        return taskdata;
    }

    // 添加初始化任务名称下拉框
    var initTaskSelect = function (projectSelectId, taskSelectId) {
        
        $("#" + projectSelectId).change(function () {
            var html = '<option value="" disabled selected style=\'display:none;\'>请选择</option>';
            var projectName = $("#" + projectSelectId).val();
            if (projectName != null) {
                var taskdatas = getAllTaskByProjectId(getProjectIdByProjectName(projectName));
                $.each(taskdatas, function (idx, item) {
                    html += "<option value='" + item.taskName + "'>" + item.taskName + "</option>";
                });
                $("#" + taskSelectId + " option").remove();
                $("#" + taskSelectId).append(html);
            }
        });
    }


    // 编辑任务名称下拉
    var editDisplayTaskName = function (selectId, pid) {
        var taskdata = [];
        var html = '';
        $.ajax({
            url: getHddcCjTaskController() + "/queryAllHddcCjTasks",//queryAllHddcCjProjects
            type: "get",
            async: false,
            success: function (data) {
                for (var i = 0; i < data.length; i++) {
                    if (data[i].belongProjectID == pid) {
                        taskdata.push(data[i]);
                    }
                }
                $.each(taskdata, function (idx, item) {
                    html += "<option value='" + item.taskId + "'>" + item.taskName + "</option>";
                });
                $("#" + selectId + " option").remove();
                $("#" + selectId).append(html);
            }
        });
    }

    var initEditTaskSelect = function (selectId, projectName) {
        
        var allTasks = getAllTask();
        var html = '<option value="" disabled selected style=\'display:none;\'>请选择</option>';
        var taskSelete = [];
        for (var i = 0; i < allTasks.length; i++) {
            if (allTasks[i].belongProject == projectName) {
                taskSelete.push(allTasks[i]);
            }
        }
        $.each(taskSelete, function (idx, item) {
            html += "<option value='" + item.taskName + "'>" + item.taskName + "</option>";
        });
        $("#" + selectId + " option").remove();
        $("#" + selectId).append(html);
    }


    var tipsInfo = function () {
        var tipsDom = $("#tips");
        var tips = "长度17位，前9位，行政区划代码6位+3位专题号，后8位自定义编码，字母数字均可，不足8位#补齐\n" +
            "3位专题号，用户自己设置。一般就是100，101，102...,201,202";
        if (tipsDom.length != 0) {
            tipsDom.attr("title", tips);
        }
    }

    var newUpload;
    var newUploadUrls = ''; //图片参数
    var imgUpload = function () {
        
        newUpload = new Cupload({
            ele: '#cupload',
            num: 10,
            data: ''
        })
        var cuploadBtn = document.getElementById('cuploadBtn')
        // $("#cuploadBtn").on("click",function(){
        cuploadBtn.addEventListener('click', function () {
            var loading = Loading({
                text: "正在加载"
            });
            var base64Info = newUpload.imageArr
            // var buildingCode = data.number
            var imageOk = true
            for (let i = 0; i < base64Info.length; i++) {
                if (base64Info[i] && !/^http/.test(base64Info[i])) {
                    const item = base64Info[i];

                    // console.log(/^data:image\/(jpg|png|gif|jpeg);base64/.test(item))
                    if (!/^data:image\/(jpg|png|gif|jpeg);base64/.test(item)) {
                        Util.alert('图片格式不支持，上传失败')
                        imageOk = false
                        return
                    }
                }
            }
            if (imageOk) {
                loading.show();
                $.ajax({
                    url: getServer() + "/hddc/pic/image64?buildingCode=" + new Date().getTime(),
                    data: JSON.stringify(base64Info),
                    type: "post",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        if (!data) {
                            setTimeout(function () {
                                loading.close();
                                Util.alert('上传失败')
                            }, 3000);
                            return
                        }
                        for (let i = 0; i < data.length; i++) {
                            const item = data[i];
                            if (!/^.*(jpg|png|gif|jpeg)$/.test(item)) {
                                Util.alert('图片格式错误，上传失败')
                                return
                            }
                        }
                        for (let i = 0; i < data.length; i++) {
                            const item = data[i];
                            // console.log(/恶意程序/.test(item))
                            if (/恶意程序/.test(item)) {
                                Util.alert('图片上传错误，请重试')
                                return
                            }
                        }
                        setTimeout(function () {
                            loading.close();
                            Util.alert('上传成功')
                        }, 3000);
                        newUploadUrls = data.join(',')
                        return newUploadUrls
                    },
                    error: function () {
                        setTimeout(function () {
                            loading.close();
                            Util.alert('上传失败')
                        }, 3000);
                        return 'error';
                    }
                });
            }
        })

    }

    var newImgUrls = '';
    var editUpload;// 回显上传组件对象
    var showImgs = function (imgUrls) {
        // console.log(data)
        if (imgUrls) {
            editUpload = new Cupload({
                ele: '#cuploadBefore',
                num: 10,
                data: imgUrls(",")
            })
            newImgUrls = imgUrls
        } else {
            editUpload = new Cupload({
                ele: '#cuploadBefore',
                num: 99,
                data:''
            })
        }
        var cuploadBtn = document.getElementById('cuploadBtn')
        cuploadBtn.addEventListener('click', function () {
            var loading = Loading({
                text: "正在加载"
            });
            var base64Info = editUpload.imageArr
            var imageOk = true
            for (let i = 0; i < base64Info.length; i++) {
                if (base64Info[i] && !/^http/.test(base64Info[i])) {
                    const item = base64Info[i];

                    // console.log(/^data:image\/(jpg|png|gif|jpeg);base64/.test(item))
                    if (!/^data:image\/(jpg|png|gif|jpeg);base64/.test(item)) {
                        Util.alert('图片格式不支持，上传失败')
                        imageOk = false
                        return
                    }
                }
            }
            if (imageOk) {
                loading.show();
                $.ajax({
                    url: getServer() + "/hddc/pic/image64?buildingCode=" + new Date().getTime(),
                    data: JSON.stringify(base64Info),
                    type: "post",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        if (!data) {
                            setTimeout(function () {
                                loading.close();
                                Util.alert('上传失败')
                            }, 3000);
                            return
                        }
                        for (let i = 0; i < data.length; i++) {
                            const item = data[i];
                            if (!/^.*(jpg|png|gif|jpeg)$/.test(item)) {
                                Util.alert('图片格式错误，上传失败')
                                return
                            }
                        }
                        newImgUrls = data.join(',')
                        setTimeout(function () {
                            loading.close();
                            Util.alert('上传成功')
                        }, 3000);
                    },
                    error: function () {
                        setTimeout(function () {
                            loading.close();
                            Util.alert('上传失败')
                        }, 3000);
                    }
                });
            }
        })
    }


    var viewFileUpload = function (fileData) {
        require(['UtilDir/fileupload/multiFileUpload'], function (MFU) {
            var attachIdData = "";
            var attachId = "";
            var fileArray = "";
            if(fileData == null){
                fileData = "";
            }
            if (fileData.length != 0) {
                fileArray = fileData.split(',');
                attachIdData = fileData.split(',');
            }
            var settings = {
                placeAt: "multiFileUpload",
                allowMC:false,
                fileSizeLimit: 1024*1024*1024,
                // accept:FILE_TYPES.packet,
                data: attachIdData,
                onUploadSuccess: function (file) {
                    attachId += file.attachId + ",";
                    if (fileData.length == 0) {
                        $("#extends8").val(attachId.substr(0, attachId.length - 1));
                    } else {
                        $("#extends8").val(fileData + "," + attachId.substr(0, attachId.length - 1));
                    }

                },
                onDeleteSavedFile: function (file) {
                    var index = fileArray.indexOf(file.attachId);
                    fileArray.splice(index, 1);
                    $("#extends8").val(fileArray.toString());
                }
            };
            var MFUpload = MFU.init(settings);

        });
    };

    var fileUpload = function () {
        require(['UtilDir/fileupload/multiFileUpload'], function (MFU) {
            var attachId = "";
            var settings = {
                placeAt: "multiFileUpload",
                allowMC:false,
                fileSizeLimit: 200*1024*1024,
                // accept:FILE_TYPES.packet,
                //data:["5a50d697c0af806aa01e06120d04f977","6c01e4492f264befab4c0532811f8dff"],
                onUploadSuccess: function (file) {
                    attachId += file.attachId + ",";
                    $("#extends8").val(attachId.substr(0, attachId.length - 1));
                },
                onDeleteSavedFile: function (file) {
                    //console.log(file)
                }
            };
            var MFUpload = MFU.init(settings);

        });
    };


    return {
        getAllProject: getAllProject,
        getAllTaskByProjectName: getAllTaskByProjectName,
        initProjectSelect: initProjectSelect,
        initTaskSelect: initTaskSelect,
        editDisplayTaskName: editDisplayTaskName,
        getAllTask: getAllTask,
        initEditTaskSelect: initEditTaskSelect,
        tipsInfo: tipsInfo,
        imgUpload: imgUpload,
        showImgs:showImgs,
        fileUpload:fileUpload,
        viewFileUpload:viewFileUpload
    };
});